package router

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"learn-go/learn-go/basic"
	"learn-go/learn-go/middleware"
	"os"
	"runtime"
	"runtime/pprof"
	"time"
)

var logger = basic.XCLogger{}

var sendMessage = middleware.XCMessage{}

func ApiIndex() gin.HandlerFunc {
	return func(c *gin.Context) {
		basic.CountRequest()
		requestPath := "/"
		sendMessage.Send(requestPath)
		c.JSON(200, gin.H{
			"message": "Hello Gin!",
		})

		//logger.Info("Request: / , Response: Hello Gin!")
	}
}

func ApiPprof() gin.HandlerFunc {
	return func(c *gin.Context) {
		basic.CountRequest()
		now := time.Now()
		go func() {
			f, err := os.Create(fmt.Sprintf("C:/Users/nixgn/Downloads/%v-cpu.prof", now.Format("20060102150405")))
			if err == nil {
				e := pprof.StartCPUProfile(f)
				if e != nil {
					logger.ERROR(fmt.Sprintf("e: %v", e))
				}
			} else {
				logger.ERROR(fmt.Sprintf("err: %v", err))
			}
			defer f.Close()
			defer pprof.StopCPUProfile()
		}()

		go func() {
			f, err := os.Create(fmt.Sprintf("C:/Users/nixgn/Downloads/%v-mem.prof", now.Format("20060102150405")))
			if err == nil {
				runtime.GC() // 获取最新的GC数据
				e := pprof.WriteHeapProfile(f)
				if e != nil {
					logger.ERROR(fmt.Sprintf("e: %v", e))
				}
			} else {
				logger.ERROR(fmt.Sprintf("err: %v", err))
			}
			defer f.Close()
		}()

		c.JSON(200, gin.H{
			"message": "ApiPprof",
		})
	}
}
